<script setup>
import {ref} from 'vue';
// 导入渠道相关api
import {getSourceTreeApi, deleteSourceApi} from '@/service/source.js';
// 导入创建视图
import SourceAdd from './components/source-add.vue';
// 导入编辑视图
import SourceEdit from './components/source-edit.vue';

// 加载渠道树
const treeData = ref([]);
const fetchTreeData = () => {
  getSourceTreeApi().then(res => {
    treeData.value = res.data.tree;
  });
};

// 显示创建视图
const sourceAddRef = ref(null);
const showCreateView = () => {
  sourceAddRef.value.openDialog();
};

// 显示编辑视图
const sourceEditRef = ref(null);
const showEditView = (row) => {
  sourceEditRef.value.openDialog(row);
};

// 删除渠道
const doDelete = (row) => {
  // 提示是否删除
  ElMessageBox.confirm('此操作将永久删除该渠道, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteSourceApi({id: row.id}).then(res => {
      fetchTreeData();
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

onMounted(() => {
  fetchTreeData();
});
</script>

<template>
  <el-main>
    <div class="toolbar">
      <el-button type="primary" @click="showCreateView">添加渠道</el-button>
    </div>
    <el-table :data="treeData" row-key="id" border>
      <el-table-column prop="id" label="编号"/>
      <el-table-column prop="title" label="渠道名称"/>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" @click="showEditView(row)">编辑</el-button>
          <el-button type="danger" @click="doDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <source-add ref="sourceAddRef" @reload="fetchTreeData"></source-add>
    <source-edit ref="sourceEditRef" @reload="fetchTreeData"></source-edit>
  </el-main>
</template>

<style scoped>

</style>